package me.shiqiang.im.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by John on 2018/7/27
 */
public class EncodeUtils {

    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

    public static String percentEncode(String value) throws UnsupportedEncodingException {
        return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null;
    }

    public static String stringToSign(HttpMethod httpMethod,String canonicalizedQueryString) throws UnsupportedEncodingException {
        return httpMethod + "&" + percentEncode("/") + "&" + percentEncode(canonicalizedQueryString);
    }



    @Value("${aliyun.live.accessKeySecret}")
    static String accessKeySecret;


    /**
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
     * @param encryptText 被签名的字符串
     * @param encryptKey  密钥
     * @return
     * @throws Exception
     */
    public static byte[] hmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
        //生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        //用给定密钥初始化 Mac 对象
        mac.init(secretKey);

        byte[] text = encryptText.getBytes(ENCODING);
        //完成 Mac 操作
        return mac.doFinal(text);
    }

    public static Map canonicalize(Map params){
        Collection<String> keySet = params.keySet();
        List<String> list = new ArrayList<>(keySet);
        Collections.sort(list);

        Map canonicalizedMap = new TreeMap();
        for (String element : list) {
            canonicalizedMap.put(element, params.get(element));
        }
        return canonicalizedMap;

    }


    public static String paramToQueryString(Map<String, String> params, String charset) throws UnsupportedEncodingException {

        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder paramString = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> p : params.entrySet()) {
            String key = p.getKey();
            String value = p.getValue();

            if (!first) {
                paramString.append("&");
            }

            // Urlencode each request parameter
            paramString.append(percentEncode(key));
            if (value != null) {
                paramString.append("=").append(percentEncode(value));
            }

            first = false;
        }

        return paramString.toString();
    }


//    public void init() throws ClientException {
//        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "<your accessKey>", "<your accessSecret>");
//        //DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "live", "live.aliyuncs.com"); //添加自定义endpoint。
//        client = new DefaultAcsClient(profile);
//        //System.setProperty("http.proxyHost", "127.0.0.1"); //此设置用于设置代理，可用fiddler拦截查看http请求，便于调试。
//        //System.setProperty("http.proxyPort", "8888");
//    }



}
